import { useUserStore } from '@/stores/user'

const BASE_URL = 'https://api.example.com/v1'
const DEFAULT_TIMEOUT = 10000 // 10秒
const MAX_RETRY_COUNT = 2 // 最大重试次数
const RETRY_DELAY = 1000 // 重试延迟1秒
const CACHE_TTL = 5 * 60 * 1000 // 5分钟缓存

// 请求缓存
const requestCache = new Map()

/**
 * 带重试的请求
 */
const requestWithRetry = (method, url, data = {}, options = {}, retryCount = 0) => {
  return new Promise((resolve, reject) => {
    const cacheKey = `${method}:${url}:${JSON.stringify(data)}`
    
    // 检查缓存 (仅GET请求)
    if (method === 'GET' && requestCache.has(cacheKey)) {
      const { data, timestamp } = requestCache.get(cacheKey)
      if (Date.now() - timestamp < CACHE_TTL) {
        return resolve({...data}) // 返回副本避免污染
      }
    }

    const userStore = useUserStore()
    const token = uni.getStorageSync('token')
    
    // 请求配置
    const config = {
      url: `${BASE_URL}${url}`,
      method,
      data,
      timeout: options.timeout || DEFAULT_TIMEOUT,
      header: {
        'Content-Type': 'application/json',
        ...(token ? { 'Authorization': `Bearer ${token}` } : {}),
        ...options.headers
      },
      success: (res) => {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          // 缓存响应 (仅GET请求)
          if (method === 'GET') {
            requestCache.set(cacheKey, {
              data: res.data,
              timestamp: Date.now()
            })
          }
          resolve(res.data)
        } else {
          handleError(res, reject, method, url, data, options, retryCount)
        }
      },
      fail: (err) => {
        handleError(err, reject, method, url, data, options, retryCount)
      }
    }

    // 发送请求
    uni.request(config)
  })
}

/**
 * 错误处理
 */
function handleError(error, reject, method, url, data, options, retryCount) {
  console.error('请求错误:', error)
  
  // 处理401未授权
  if (error.statusCode === 401) {
    const userStore = useUserStore()
    userStore.logout()
    uni.showToast({
      title: '登录已过期，请重新登录',
      icon: 'none'
    })
    uni.navigateTo({
      url: '/pages/login/login'
    })
    return reject(new Error('登录已过期'))
  }
  
  // 可重试的错误 (网络错误或5xx错误)
  const isRetryable = !error.statusCode || 
    (error.statusCode >= 500 && error.statusCode < 600)
  
  if (isRetryable && retryCount < MAX_RETRY_COUNT) {
    setTimeout(() => {
      requestWithRetry(method, url, data, options, retryCount + 1)
        .then(resolve)
        .catch(reject)
    }, RETRY_DELAY)
  } else {
    // 最终错误处理
    const errorMap = {
      400: '请求参数错误',
      403: '没有权限访问',
      404: '资源不存在',
      500: '服务器错误',
    }
    
    const message = errorMap[error.statusCode] || 
      error.errMsg || 
      '请求失败'
      
    reject(new Error(message))
  }
}

// GET请求
export const get = (url, params = {}, options = {}) => {
  return request('GET', url, params, options)
}

// POST请求
export const post = (url, data = {}, options = {}) => {
  return request('POST', url, data, options)
}

// PUT请求
export const put = (url, data = {}, options = {}) => {
  return request('PUT', url, data, options)
}

// DELETE请求
export const del = (url, data = {}, options = {}) => {
  return request('DELETE', url, data, options)
}

export default {
  get,
  post,
  put,
  delete: del
}